package edu.uoc.tdp.pac4.database;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;



import edu.uoc.tdp.pac4.beans.Usuari;
import edu.uoc.tdp.pac4.beans.Rol;


/**
 * Class to manage the users log in 
 */

public class LoginManager {

	
	private static Connection con;
	private static PreparedStatement ptmt = null;
	private static ResultSet rs = null;
	DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

	public LoginManager() {
		super();
	}
	
	
	public static Usuari login(String username, String password){

		
		String q = null;
		
		try {

			con = DiskManager.getInstance().getConnection();		
			q = "select * from usuari where loginusuari = ? and contrasenya = ?";
			
			ptmt = con.prepareStatement(q);
			ptmt.setString(1, username);
			ptmt.setString(2, password);
			rs = ptmt.executeQuery();
			
			if (rs.next()){
							 
				Usuari usr = new Usuari(
							rs.getString("nif"), 
							rs.getString("nom"),
							rs.getString("email"),
							rs.getString("cognoms"),  
							null, 
							null, 
							username, 
							password, 
							getUserRole((String)rs.getString("rolusuari")));
				return usr;
				}
					
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				ptmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	private static Rol getUserRole(String rolFromBd){
		if(rolFromBd != null && !"".equals(rolFromBd)){
			if(rolFromBd.equals(RoleHelper.ALUMNE)){
				return Rol.Alumne;
			}else if(rolFromBd.equals(RoleHelper.ADMINISTRADOR)){
				return Rol.Administrador;
			}else if(rolFromBd.equals(RoleHelper.PERS_ACADEMIC)){
				return Rol.Personal_Academic;
			}else if(rolFromBd.equals(RoleHelper.PROFESSOR)){
				return Rol.Professor;
			}
		}
		//Per defecte...
		return Rol.Alumne;
	}
}

